package com.rgzn.chapter3_3.controller;

import com.rgzn.chapter3_3.entity.User;
import com.rgzn.chapter3_3.service.LoginService;
import com.rgzn.chapter3_3.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Controller
public class UserController {
    //打开主页
    @RequestMapping(value = {"/index","/main"})
    public String index(){
        log.info("打开主页");
        return "index";
    }
    //打开登陆界面
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView login(ModelAndView mv){
        log.info("打开登陆界面");
        mv.setViewName("login");
        return mv;
    }

    //登陆验证
    @Autowired
    private LoginService loginService;
    @RequestMapping(value = "/login",params = {"name","password"},name = "登陆验证",method = RequestMethod.POST)
//    @ResponseBody
    public ModelAndView userlogin(ModelAndView mv,User user){
        log.info(":"+user);
        if (loginService.login(user.getName(), user.getPassword())){
            mv.setViewName("index");
            mv.addObject("users",user);
        }else {
            mv.setViewName("login");
            mv.addObject("error","登陆失败");
        }
        return mv;
    }


    //处理访问登陆页面的请求
    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public ModelAndView showregister(ModelAndView modelAndView){
//        ModelAndView modelAndView = new ModelAndView();
        //设置访问的界面
        modelAndView.setViewName("register");
        //设置数据
        modelAndView.addObject("user", new User());
        return modelAndView;
    }

    //处理注册数据
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public ModelAndView handleregister(ModelAndView modelAndView,User user){
        try {
            userService.register(user);
            modelAndView.addObject("success","注册成功");
        } catch (Exception e) {
            modelAndView.addObject("error","注册失败");
            log.error(e.getMessage());
        }
        return modelAndView;
    }
}
